package com.kun.service.service.impl;

import com.kun.dto.PageTable;
import com.kun.dto.TaskDto;
import com.kun.service.service.IProcessDefinitionService;
import com.kun.service.service.IProcessInstanceService;
import com.kun.service.service.ITaskService;
import com.kun.utils.BpmnUtils;
import com.kun.vo.TaskVo;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.model.payloads.ClaimTaskPayload;
import org.activiti.api.task.model.payloads.CompleteTaskPayload;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TaskServiceImpl implements ITaskService {

    private final IProcessInstanceService processInstanceService;
    private final TaskRuntime taskRuntime;
    private final RepositoryService repositoryService;
    private final IProcessDefinitionService processDefinitionService;

    public TaskServiceImpl(IProcessInstanceService processInstanceService, TaskRuntime taskRuntime,
                           RepositoryService repositoryService, IProcessDefinitionService processDefinitionService) {
        this.processInstanceService = processInstanceService;
        this.taskRuntime = taskRuntime;
        this.repositoryService = repositoryService;
        this.processDefinitionService = processDefinitionService;
    }

    @Override
    public PageTable myTasks(TaskDto taskDto) {
        Page<Task> tasks = taskRuntime.tasks(Pageable.of(taskDto.getCurrent() - 1, taskDto.getPageSize()));
        List<Task> content = tasks.getContent();
        if (content.isEmpty()) return new PageTable(List.of(), 0L);

        // 查询所有流程实例
        List<ProcessInstance> instanceList = processInstanceService.getInstanceList();
        List<TaskVo> list = content.stream().map(task -> {
            ProcessInstance processInstanceById = processInstanceService.findProcessInstanceById
                    (instanceList, task.getProcessInstanceId());
            return new TaskVo(task.getId(), task.getAssignee() == null ? "待拾取任务" : task.getAssignee(),
                    task.getName(), task.getCreatedDate(), processInstanceById.getName(), task.getStatus());
        }).toList();
        // 总条数
        int totalItems = tasks.getTotalItems();
        return new PageTable(list, (long) totalItems);
    }

    /**
     * 完成任务
     */
    @Override
    public boolean completeTask(String taskId) {
        // 查询任务
        Task task = taskRuntime.task(taskId);
        if (task.getAssignee() == null) {
            // 不需要先拾取任务，再执行（表示是候选人）
            ClaimTaskPayload build = TaskPayloadBuilder.claim().withTaskId(taskId).build();
            // 拾取任务
            taskRuntime.claim(build);
        }
        // 完成任务
        CompleteTaskPayload build = TaskPayloadBuilder.complete().withTaskId(taskId)
                // 可以完成时加参数
//                .withVariables()
                .build();
        taskRuntime.complete(build);
        return true;
    }

    /**
     * 渲染动态表单
     */
    @Override
    public Object getDynamicForm(String taskId) {
        // 根据ID获取任务
        Task task = taskRuntime.task(taskId);
        // 根据任务的流程定义ID获取该任务的BPMN模型
//        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        // 从BPMN模型中根据任务的FormKey获取对应的流程元素
//        UserTask userTask = (UserTask) bpmnModel.getFlowElement(task.getFormKey());
//        if (userTask == null) return null;
        // 获取 bpmnjs xml
        ProcessDefinition processDefinition = processDefinitionService.selectByDefinitionId(task.getProcessDefinitionId());
        String xml = processDefinitionService.getXml(processDefinition.getDeploymentId(),
                processDefinition.getResourceName());
        // 解析XML，获取控件
        return BpmnUtils.getFormKey(xml, task.getFormKey());
    }
}
